package com.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dbconnect.DBConnectionMgr;
import com.google.gson.Gson;
import com.vo.Score;

/**
 * Servlet implementation class dataList
 */
@WebServlet("/dataList")
public class dataList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		DBConnectionMgr dbconn = DBConnectionMgr.getInstance();
			
		try {
			Gson gson = new Gson();
			String json = null;
			List<Score> list = new ArrayList<Score>();			
			conn = dbconn.getConnection();

			String sql = "SELECT * FROM algorithm";

			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			
			while(rs.next()){
				Score score = new Score();
				score.setHakbun(rs.getString("hakbun"));
				score.setName(rs.getString("name"));
				score.setChasu(rs.getString("chasu"));
				score.setCriminal(rs.getInt("criminal"));
				score.setCivil(rs.getInt("civil"));
				score.setEnglish(rs.getInt("english"));
				score.setAverage(rs.getDouble("average"));
				score.setRank(rs.getString("rank"));
				list.add(score);
			}
			json = gson.toJson(list);
			
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(json);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbconn.freeConnection(conn, ps, rs);
		}
		
	}

}
